<?php
/**
 * Created by 784855684@qq.com.
 * Link: https://github.com/lichtung/wshore
 * User: linzh
 * Date: 7/8/17
 * Time: 8:35 AM
 */
declare(strict_types=1);


namespace application\module\admin\addon\rbca\model;


use application\module\admin\addon\model\AddonModel;

class UserRoleModel extends AddonModel
{
    protected function tableName()
    {
        return 'rel_user_role';
    }

    protected function tablePrefix()
    {
        return 'ws_auth_';
    }

    protected function struct(): string
    {
        return " `uid` int(10) unsigned NOT NULL COMMENT 'user id',
  `rid` int(10) unsigned NOT NULL COMMENT 'role id',
  PRIMARY KEY (`uid`,`rid`),
  KEY `rel_member_role2` (`rid`),
  KEY `mid` (`uid`)";
    }

    /**
     * 查询用户的角色列表
     * SELECT prr.*,IFNULL(prrr.rid,0) as role,prr.id as mid
     * FROM l_auth_role prr
     * LEFT OUTER JOIN l_auth_rel_user_role prrr on prrr.mid = prr.id and prr.id = 2
     *
     * @param int $uid 用户ID
     * @return array
     */
    public function getUserRoles(int $uid): array
    {
        $uid = intval($uid);
        $list = $this->fields("r.*,IFNULL(rr.rid,0) as role,{$uid} as uid")
            ->table('{{role}} r')
            ->leftOuterJoin("{{rel_user_role}} rr on rr.rid = r.id and rr.uid = {$uid}")
            ->select();
        return $list;
    }

    /**
     * 获取拥有改角色的客户列表
     * @param int $rid
     * @return array
     */
    public function getRoleUsersIds(int $rid): array
    {
        $list = $this->where(['rid' => $rid])->select();
        $reslist = [];
        foreach ($list as $item) {
            $reslist[] = (int)$item['uid'];
        }
        return $reslist;
    }

}